<script setup lang="ts">
import {useStore} from "vuex";
import {computed, ref} from "vue";
import {CustomGridList} from "@/interfaces/custom-grid";
import type {Operation} from "@/interfaces/user";
import {onShow} from "@dcloudio/uni-app";
import {useOrderCountApi, useUpdateAvatarApi} from "@/services/api";

const store = useStore()
const uToastRef = ref()
const show = ref<boolean>(false)
const avatar = computed(() => store.getters["auth/getAvatar"])
const username = computed(() => store.getters["auth/getUsername"])
const isLogin = computed(() => store.getters["auth/getIsLogin"])
const bookRecordList = ref<CustomGridList[]>([
  {
    id: 0,
    label: '全部',
    name: 'total',
    count: 0
  },
  {
    id: 1,
    label: '已预约',
    name: 'booked',
    count: 0
  },
  {
    id: 2,
    label: '已完成',
    name: 'finished',
    count: 0
  },
  {
    id: 3,
    label: '已取消',
    name: 'canceled',
    count: 0
  }
])
const list = ref<Operation[]>([
  {
    name: '退出登录',
    operation: async () => {
      await store.dispatch('auth/logout', (callback: () => void): void => {
        uToastRef.value.show({
          message: '已退出登录,请重新登录!',
          type: 'success',
          complete: () => {
            show.value = false
            callback()
          }
        })
      })
    }
  },
  {
    name: '更换头像',
    operation: async () => {
      uni.chooseImage({
        count: 1,
        success: res => {
          const imageUrl = res.tempFilePaths[0]; // 返回选定照片的本地文件路径列表
          uni.uploadFile({
            url: 'http://localhost/api/admin/upload',
            filePath: imageUrl,
            name: 'file',
            header: {
              'content-type': 'multipart/form-data',
              'Authorization': store.getters["auth/getToken"]
            },
            success: async res => {
              const {code, data} = JSON.parse(res.data)
              await useUpdateAvatarApi({userId: store.getters["auth/getUserId"], avatar: data})
              await store.dispatch("auth/setAvatar", data)
              uToastRef.value.show({
                type: 'success',
                message: "更换成功",
              })
            }
          });
        }
      })
    }
  }
])
const goLoginOrLogout = () => {
  if (!isLogin.value) {
    uni.$u.route('/pages/login/login')
  } else {
    show.value = true
  }
}
const selectAction = (index: Operation) => {
  index.operation()
}
const init = async () => {
  const {data: res} = await useOrderCountApi({userId: store.getters["auth/getUserId"]})
  bookRecordList.value.forEach(item => {
    item.count = res[item.name]
  })
}
onShow(() => {
  init()
})

</script>

<template>
  <view class="container">
    <u-toast ref="uToastRef"></u-toast>
    <custom-tabbar></custom-tabbar>
    <view class="user-info-card">
      <view class="user-avatar">
        <up-avatar
            :src="avatar"
            default-url="/static/avatar.webp"
            shape="circle"
            size="64px"
        ></up-avatar>
      </view>
      <view class="username" @tap="goLoginOrLogout">
        {{ username || '立即登录' }}
        <span>
          <u-icon name="arrow-right" size="20px"></u-icon>
        </span>
      </view>
    </view>
    <view class="book-record-card">
      <custom-grid :list="bookRecordList"></custom-grid>
    </view>
    <u-action-sheet :actions="list" :closeOnClickAction="true" :closeOnClickOverlay="true" :show="show"
                    title="操作" @close="show = false" @select="selectAction"></u-action-sheet>
  </view>
</template>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 12px;

  .user-info-card {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 24px;
    border-radius: 12px;
    background-color: #ffffff;
    padding: 12px 24px;

    .username {
      display: flex;
      flex-direction: row;
      gap: 10px;
      align-items: center;
      font-size: 20px;
      font-weight: bold;
    }
  }

  .book-record-card {
    padding: 24px 12px;
    background-color: #ffffff;
    border-radius: 12px;
  }
}
</style>